/*
 * @(#)RoleAction.java
 * 2011-5-9 下午09:13:34
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.accountmng.web;

import java.util.List;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.qyxx.platform.common.json.JsonOutput;
import com.qyxx.platform.common.module.service.ServiceException;
import com.qyxx.platform.common.module.web.CrudActionSupport;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.utils.web.struts2.Struts2Utils;
import com.qyxx.platform.sysmng.accountmng.entity.Authority;
import com.qyxx.platform.sysmng.accountmng.entity.Organization;
import com.qyxx.platform.sysmng.accountmng.entity.OrganizationJson;
import com.qyxx.platform.sysmng.accountmng.entity.Role;
import com.qyxx.platform.sysmng.accountmng.entity.RoleJson;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.accountmng.service.AccountManager;
import com.qyxx.platform.sysmng.accountmng.service.OrganizationManager;
import com.qyxx.platform.sysmng.accountmng.service.ResourceCacheService;
import com.qyxx.platform.sysmng.utils.Constants;

/**
 * 角色管理Action.
 * 
 * @author gxj
 * @version 1.0
 * @since 1.6 2011-5-9 下午09:13:34
 */
@Namespace("/sys/account")
@Results({
		@Result(name = CrudActionSupport.RELOAD, location = "role.action", type = "redirect"),
		@Result(name = "rolelist", location = "/WEB-INF/content/sys/account/role.jsp") })
public class RoleAction extends CrudActionSupport<Role> {
	
	public static final String SAVE_USER_ROLE = "saveUserRole";

	private static final long serialVersionUID = -4052047494894591406L;

	private AccountManager accountManager;
	private OrganizationManager organizationManager;
	private ResourceCacheService resourceCacheService;
	// -- 页面属性 --//
	private Long id;
	private Long orgId;
	private Long[] ids;
	private Role entity;
	private List<Role> allRoleList;// 角色列表
	private List<Long> checkedAuthIds;// 页面中钩选的权限id列表
	private String authorityIds;
	private String userId;
	private String desktopIds;
	private String method = "";
	private String roleName;
	private String systemTypeIds;
	
	private String seeUserIds;//可见用户ID
	
	
	public String getSystemTypeIds() {
		return systemTypeIds;
	}


	
	public void setSystemTypeIds(String systemTypeIds) {
		this.systemTypeIds = systemTypeIds;
	}


	public String getRoleName() {
		return roleName;
	}

	
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	/**
	 * @return method
	 */
	public String getMethod() {
		return method;
	}

	public Long getOrgId() {
		return orgId;
	}

	public void setOrgId(Long orgId) {
		this.orgId = orgId;
	}


	/**
	 * @param method
	 */
	public void setMethod(String method) {
		this.method = method;
	}


	public String getUserId() {
		return userId;
	}

	
	public void setUserId(String userId) {
		this.userId = userId;
	}


	public String getAuthorityIds() {
		return authorityIds;
	}

	
	public void setAuthorityIds(String authorityIds) {
		this.authorityIds = authorityIds;
	}

	public String getDesktopIds() {
		return desktopIds;
	}

	
	public void setDesktopIds(String desktopIds) {
		this.desktopIds = desktopIds;
	}
	
	/**
	 * @return seeUserIds
	 */
	public String getSeeUserIds() {
		return seeUserIds;
	}

	/**
	 * @param seeUserIds
	 */
	public void setSeeUserIds(String seeUserIds) {
		this.seeUserIds = seeUserIds;
	}



	// -- ModelDriven 与 Preparable函数 --//
	public Role getModel() {
		return entity;
	}

	public void setId(Long id) {
		this.id = id;
	}

	
	/**
	 * @return ids
	 */
	public Long[] getIds() {
		return ids;
	}

	
	/**
	 * @param ids
	 */
	public void setIds(Long[] ids) {
		this.ids = ids;
	}

	@Autowired
	public void setOrganizationManager(
			OrganizationManager organizationManager) {
		this.organizationManager = organizationManager;
	}
	
	@Autowired
	public void setResourceCacheService(
			ResourceCacheService resourceCacheService) {
		this.resourceCacheService = resourceCacheService;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = accountManager.getRole(id);
		} else {
			entity = new Role();
		}
	}

	// -- CRUD Action 函数 --//
	@Override
	public String list() throws Exception {
		allRoleList = accountManager.getAllRole();
		return SUCCESS;
	}

	@JsonOutput
	public String queryList() throws Exception {
		List<PropertyFilter> filters = PropertyFilter
				.buildFromHttpRequest(Struts2Utils.getRequest());
//		PropertyFilter propertyFilterStatus = new PropertyFilter(
//				"EQS_roleStatus", Constants.IS_USING);
//		filters.add(propertyFilterStatus);
		if (orgId != null) {
			/*String ids = this.accountManager.getStringOrgSonId(orgId);
			PropertyFilter propertyFilterParentOrg = new PropertyFilter(
					"INL_organization.id", ids);
			filters.add(propertyFilterParentOrg);*/
			String code = this.accountManager.findOrganization(orgId).getOrganizationCode();
			PropertyFilter propertyFilterParentOrg = new PropertyFilter(
					"LIKELS_com.qyxx.platform.sysmng.accountmng.entity.Organization$$$organization.organizationCode", code);
			filters.add(propertyFilterParentOrg);
		}
		pager = accountManager.searchRole(pager, filters);
		Struts2Utils.renderJson(pager);
		return null;
	}

	@Override
	public String input() throws Exception {
		checkedAuthIds = entity.getAuthIds();
		return INPUT;
	}

	/**
	 * 保存角色，角色保存使用
	 * @see com.qyxx.platform.common.module.web.CrudActionSupport#save()
	 */
	@Override
	@JsonOutput
	public String save() throws Exception {
		//角色保存
		String organizationId = Struts2Utils
				.getParameter("organizationId");
		if (organizationId == null || "".equals(organizationId)) {
			organizationId = "1";
		}
		Organization org = this.organizationManager
				.getOrganizationById(Long.valueOf(organizationId));
		entity.setOrganization(org);
		if(SAVE_USER_ROLE.equals(method)) {
			//保存用户权限
			accountManager.saveUserAndRole(entity,authorityIds,userId,desktopIds,systemTypeIds, seeUserIds);
			//刷新资源缓存
			//resourceCacheService.refreshResource();
		} else {
			//保存角色权限
			accountManager.saveRole(entity,authorityIds,desktopIds,systemTypeIds, seeUserIds);
		}
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
/*	*//**
	 * 保存用户与角色，授权功能使用
	 * @see com.qyxx.platform.common.module.web.CrudActionSupport#save()
	 *//*
	@JsonOutput
	public String saveUserAndRole() throws Exception {
		//角色保存
		String organizationId = Struts2Utils
				.getParameter("organizationId");
		if (organizationId == null || "".equals(organizationId)) {
			organizationId = "1";
		}
		Organization org = this.organizationManager
				.getOrganizationById(Long.valueOf(organizationId));
		entity.setOrganization(org);
		accountManager.saveUserAndRole(entity,authorityId, userId);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}*/

	@Override
	@JsonOutput
	public String delete() throws Exception {
		accountManager.deleteRole(id);
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);

		return null;
	}
	@JsonOutput
	public String deleteRoles() throws Exception {
		
		if (ids==null) {
			throw new ServiceException("请选择你要删除的角色", new Exception(
					"请选择你要删除的角色"));
		}
		for(Long id : ids) {
			accountManager.deleteRole(id);
		}
		formatMessage.setMsg(true);
		Struts2Utils.renderJson(formatMessage);

		return null;
	}
	// -- 页面属性访问函数 --//
	/**
	 * list页面显示所有角色列表.
	 */
	public List<Role> getAllRoleList() {
		return allRoleList;
	}

	/**
	 * input页面显示所有授权列表.
	 */
	public List<Authority> getAllAuthorityList() {
		return accountManager.getAllAuthority();
	}

	/**
	 * input页面显示角色拥有的授权.
	 */
	public List<Long> getCheckedAuthIds() {
		return checkedAuthIds;
	}

	/**
	 * input页面提交角色拥有的授权.
	 */
	public void setCheckedAuthIds(List<Long> checkedAuthIds) {
		this.checkedAuthIds = checkedAuthIds;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	@Override
	public String view() throws Exception {
		// TODO Auto-generated method stub
		entity = accountManager.getRole(id);
		formatMessage.setMsg(entity);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	@JsonOutput
	public String modifyInfo() throws Exception {
		entity = accountManager.getRole(id);
		formatMessage.setMsg(entity);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	@JsonOutput
	public String addInfo() throws Exception {
		
		if (orgId==null) {
//			throw new ServiceException("请选择你要添加角色所属的组织", new Exception(
//					"请选择你要添加角色所属的组织"));
			orgId=new Long(1);
		}
		Organization org = organizationManager.getOrganizationById(orgId);
		OrganizationJson organizationJson = new OrganizationJson();
		organizationJson.setParentId(orgId);
		organizationJson.setParentName(org.getOrganizationName());
		formatMessage.setMsg(organizationJson);
		Struts2Utils.renderJson(formatMessage);

		return null;
	}

	public String init() throws Exception {
		return "rolelist";
	}
	@JsonOutput
	public String roleList()  {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		Long userId = user.getId();
		List<RoleJson> list = accountManager.getList(userId);
		formatMessage.setMsg(list);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	@JsonOutput
	public String getOrgList() {
		User user = (User)Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		Long userId = user.getId();
		List<RoleJson> list = accountManager.getList(userId,false);
		formatMessage.setMsg(list);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	@JsonOutput
	public String validateName() throws Exception {
		Boolean flag = accountManager.validateRole(roleName,id);
		formatMessage.setMsg(flag);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
}